package com.foruo.learn.designmode.proxy.cglibProxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * cglib动态代理
 * @author GaoYuan
 */
public class PersonCglibProxy implements MethodInterceptor{

    private Object target;

    public PersonCglibProxy(Object target){
        this.target = target;
    }

    /** 创建代理对象 */
    public Object getProxyInstance(){
        //cglib 的代理工具类
        Enhancer en = new Enhancer();
        //设置父类
        en.setSuperclass(target.getClass());
        //设置回调方法
        en.setCallback(this);
        //创建子类对象
        return en.create();
    }
    
    /**
     * 实现接口的拦截方法
     * @author GaoYuan
     */
    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        System.out.println("开始做饭");
        Object o = method.invoke(target,args);
        System.out.println("收拾碗筷");
        return o;
    }
}
